﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

using iTool.Cloud.Center.DataEntity;
using iTool.Cloud.Center.Model;

using Microsoft.Data.Sqlite;

using Newtonsoft.Json;

namespace iTool.Cloud.Center.ServiceProvider.StorageProvider
{
    internal static class iStorage
    {
        // Reminder
        internal static iStorageReminderMaster GetClusterReminders(string cluster) => iStorageReminderMaster.GetStorageMasterProvide(cluster);

        // Membership
        internal static iStorageMembershipMaster GetClusterMemberships(string cluster) => iStorageMembershipMaster.GetStorageMasterProvide(cluster);

        // Storage
        internal static iStorageStateMaster GetClusterStorages(string cluster) => iStorageStateMaster.GetStorageMasterProvide(cluster);

        // Transactional
        internal static iStorageTransactionalMaster GetClusterTransactional(string cluster) => iStorageTransactionalMaster.GetStorageMasterProvide(cluster);
        internal static Task BatchWriteAsync(string cluster, string type, object value)
        {
            string SQL = "update KeyValues set Value=@Value where Cluster=@Cluster and Type=@Type";
            iSqliteProvide.ExecuteNonQuery(SQL, parameters: new SqliteParameter[]
                            {
                                new SqliteParameter("@Cluster", cluster),
                                new SqliteParameter("@Type", type),
                                new SqliteParameter("@Value", JsonConvert.SerializeObject(value)),
                            });
            //System.IO.File.WriteAllText($"./{type}_{cluster.Replace(":", "").Replace(",", "_")}.txt", JsonConvert.SerializeObject(value));
            return Task.CompletedTask;
        }
        internal static KeyValues GetKeyValue(string cluster, string type)
        {
            var keyValue = iSqliteProvide.ExecuteQuery<KeyValues>(
                        "select * from KeyValues where Cluster=@Cluster and Type=@Type limit 1"
                        , new SqliteParameter("@Cluster", cluster)
                        , new SqliteParameter("@Type", type));

            if (string.IsNullOrEmpty(keyValue.Cluster))
            {
                iSqliteProvide.ExecuteNonQuery(
                    "insert into KeyValues(Cluster,Type) values(@Cluster,@Type)"
                    , parameters: new SqliteParameter[]
                    {
                                new SqliteParameter("@Cluster", cluster),
                                new SqliteParameter("@Type", type)
                    });
            }

            return keyValue;
        }
    }

}
